package com.controller;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.entity.Category;
import com.google.gson.Gson;
import com.service.CategoryService;
/**
 * 分类控制层
 * @author MingCha Yang
 *
 */
@Controller @RequestMapping("/category")
public class CategoryController {
	@Resource
	private CategoryService categoryService;
	@RequestMapping("/chirdname")
	public void returnChirdname(Integer articleParentCategoryId,HttpServletResponse rep) {
		List<Category> categorylistByCategoryPid = categoryService.getCategorylistByCategoryPid(articleParentCategoryId);
		try {
			Gson gson = new Gson();
			String json = gson.toJson(categorylistByCategoryPid);
			rep.getWriter().write(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@RequestMapping("/categoryPage")
	public String gotocategoryPage(ModelMap m) {
		List<Category> categorys = categoryService.getCategoryList();
		List<Category> categorylistByZero = categoryService.getCategorylistByCategoryPid(0);
		m.put("categorys",categorys);
		m.put("categorylistByZero",categorylistByZero);
		
		return "Category/category-page";
	}
	@RequestMapping("insertSubmit")
	public String addCategory(Category category) {
		category.setCategoryOrder(1);
		categoryService.addCategory(category);
		return "redirect:/category/categoryPage";
	}
	@RequestMapping("/delete/{categoryId}")
	public String deleteCategory(@PathVariable("categoryId") Integer categoryId) {
		Category c = categoryService.getCategoryBycategoryId(categoryId);
		categoryService.deletCategoryBycategoryId(categoryId);
		if(c.getCategoryPid()==0) {
			categoryService.deletCategoryBycategoryPid(categoryId);
		}
		return "redirect:/category/categoryPage";
	}
    @RequestMapping("/updateAjax")
    public void updateAjax(Integer categoryId,HttpServletResponse response) throws IOException {
    	Category category = categoryService.getCategoryBycategoryId(categoryId);
    	Gson gson = new Gson();
    	String json = gson.toJson(category);
    	response.getWriter().write(json);
    }
    @RequestMapping("/updateSubmit")
    public void updateSubmit(Category category,HttpServletResponse response) throws IOException {
    	category.setCategoryOrder(1);
    	categoryService.updateCategoryBycategoryId(category);
    	response.getWriter().write("success");
    }
}
